package com.deer.wms.instock.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.ASN.manage.dao.AsnMasterMapper;
import com.deer.wms.ASN.manage.model.asn.AsnDetail;
import com.deer.wms.ASN.manage.model.asn.AsnMaster;
import com.deer.wms.ASN.manage.model.in.AcceptInsert;
import com.deer.wms.ASN.manage.service.AsnCodeDetailService;
import com.deer.wms.ASN.manage.service.AsnDetailService;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.ASN.manage.service.impl.AcceptRecordServiceImpl;
import com.deer.wms.base.system.service.CellInfoService;
import com.deer.wms.instock.service.WaveService;
import com.deer.wms.instock.service.enter.StrategyEnterService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.InventoryCriteria;
import com.deer.wms.inventory.model.Inventory.InventorySelectDto;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.system.manage.service.CodeRuleService;
import com.deer.wms.ware.task.config.StrategyErpService;
import com.deer.wms.ware.task.erp.UpdatePPF;
import com.deer.wms.ware.task.model.SO.SoDetail;
import com.deer.wms.ware.task.model.SO.SoMaster;
import com.deer.wms.ware.task.model.Wave.WaveDetail;
import com.deer.wms.ware.task.model.out.OutDetail;
import com.deer.wms.ware.task.model.pickTask.*;
import com.deer.wms.ware.task.model.pushErp.beasAssist.BaseAssist;
import com.deer.wms.ware.task.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.deer.wms.project.root.util.CollectionUtils.convertMap;

/**
 * @Author: xu
 * @Date: 2022/06/23/11:27
 * @Description:
 */
@Service
@Transactional
public class WaveServiceImpl implements WaveService {
    @Autowired
    private WaveDetailService waveDetailService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private TransferBillServiceImpl transferBillService;
    @Autowired
    private AcceptRecordServiceImpl acceptRecordService;
    @Autowired
    private AsnDetailService asnDetailService;
    @Autowired
    private CellInfoService cellInfoService;
    @Autowired
    private AsnMasterMapper asnMasterMapper;
    @Autowired
    private StrategyEnterService strategyEnterService;
    @Autowired
    private SoMasterService soMasterService;
    @Autowired
    private CodeRuleService codeRuleService;

    @Autowired
    private SoDetailService soDetailService;

    @Autowired
    private AsnCodeDetailService asnCodeDetailService;

    @Autowired
    private PushErpService pushErpService;

    @Value("${wave.direct}")
    //直发虚仓
    private Integer directId;

    @Value("${wave.start}")
    //直发虚仓
    private Integer start;

    @Value("${wave.vmi}")
    //VMI仓库id
    private Integer vmiId;

    @Autowired
    private WaveServiceImpl waveService;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private StrategyErpService strategyErpService;



//    }

    @Override
    @Transactional

    public void accomplish(AsnMaster asnMaster, String cellCode, CurrentUser currentUser, Double qty, String batchName) {
        //齐套性检查
        if (soMasterService.dispatch(asnMaster.getBillNo())) {
            SoMaster soMaster = soMasterService.getOne(new QueryWrapper<SoMaster>().eq("order_bill_no", asnMaster.getBillNo()).last("limit 1"));
            if (ObjectUtil.isNotEmpty(soMaster)) {
                soMaster.setDispatch(1);
                asnMaster.setDispatch(1);
                //异步修改需要齐套
                CompletableFuture.runAsync(() -> {
                    asnMasterMapper.updateById(asnMaster);
                });
            }
        }

        Integer areaId = cellInfoService.findbyCellCode(cellCode);
        List<AcceptInsert> acceptInserts = new ArrayList<>();
        // 现在加上了一个上架数量--只上架部分的数量--前提是产成品入库只有一个明细数据
        List<AsnDetail> asnDetails = asnDetailService.findByBillNo(asnMaster.getBillNo());
        for (AsnDetail detail : asnDetails) {
            //批号任务单号当批号
            detail.setBatchName(batchName);
            detail.setStockId(areaId);
            detail.setQty(detail.getExpectQuantity());
            AcceptInsert acceptInsert = new AcceptInsert();
            //履约号
            acceptInsert.setAgreementNo(asnMaster.getAgreementNo());
            acceptInsert.setWareId(asnMaster.getWareId());
            acceptInsert.setWareName(asnMaster.getWareName());
            acceptInsert.setItemName(detail.getItemName());
            acceptInsert.setItemCode(detail.getItemCode());
            acceptInsert.setToBoxCode(codeRuleService.generateCellCodeRedis());
            acceptInsert.setBatchName(batchName);
            acceptInsert.setToPackDetailId(detail.getPackDetailId());
            acceptInsert.setToPackDescribe(detail.getPackDescribe());
            acceptInsert.setToTransRatio(detail.getTransRatio());
            // 这里的数量是前台填写的数量 detail.getExpectQuantity()->qty
            acceptInsert.setToQuantity(qty);
            acceptInsert.setToCellCode(cellCode);
            acceptInsert.setAcceptUserId(currentUser.getUserId());
            acceptInsert.setAcceptUserName(currentUser.getUserName());
            acceptInsert.setAcceptTime(DateUtil.now());
            acceptInsert.setBillType(0);
            acceptInsert.setAsnDetailNo(detail.getDetailNo());
            acceptInsert.setAsnBillNo(detail.getBillNo());
            // 质检-0
            acceptInsert.setQcState(0);
            acceptInserts.add(acceptInsert);
            // 设置回传数量
            detail.setQty(qty);
        }
        //Step1.创建收货单并确认
        acceptRecordService.saveAndConfirmAcceptRecord(acceptInserts);


        //Step2.入库回传

        strategyEnterService.resolveAsn(asnMaster, asnDetails, new BaseAssist());

    }

    @Autowired
    InventoryTransactService inventoryTransactService;

    @Transactional
    public void bathServer() {
        List<Inventory> inventories = inventoryService.list(new QueryWrapper<Inventory>()

             
        );



    }


    @Override
    public void virtual(Long id, CurrentUser currentUser, Double vmiNumber) {
        WaveDetail waveDetail = waveDetailService.getById(id);

        List<Inventory> inventories = inventoryService.list(new QueryWrapper<Inventory>()
                .in("item_code", waveDetail.getItemCode())
                .eq("asn_stock_id", directId)
                .notIn("cell_code", 285000, 285333)
                .orderByDesc("modify_time")
        );
        if (ObjectUtil.isNotEmpty(inventories)) {
            return;
        }
        //Step1.入库
        waveService.inputBank(inventories, vmiNumber);
        //Step2.出库
        transferBillService.virtual(id, currentUser, vmiNumber);
    }

    /**
     * 直发虚仓出库
     *
     * @param soDetail
     * @param currentUser
     */
    @Override
    public void virtualSoDetail(SoDetail soDetail, CurrentUser currentUser) {
        //发货数量-订货数量=剩余一键出库数量
        soDetail.setDeliveryQuantity(soDetail.getOrderQuantity() - soDetail.getDeliveryQuantity());
        WaveDetail waveDetail = waveDetailService.getById(soDetail.getWaveDetailId());
        //剩余数量
        waveDetail.setQuantity(waveDetail.getQuantity() - soDetail.getDeliveryQuantity());
        soDetail.setWaveDetailId(null);
        List<Inventory> inventories = inventoryService.list(new QueryWrapper<Inventory>()
                .in("item_code", waveDetail.getItemCode())
                .eq("asn_stock_id", directId)
                .notIn("cell_code", 285000, 285333)
                .orderByDesc("modify_time")
        );

        //Step1.入库
        waveService.inputBank(inventories, soDetail.getDeliveryQuantity());
//        Step2.出库
        transferBillService.virtualSoDetail(soDetail, currentUser);
    }


    @Autowired
    private AsnMasterService asnMasterService;

    /**
     * VMI入库
     *
     * @param list
     * @param currentUser
     */
    @Override
    public void inventoryVmi(List<Inventory> list, CurrentUser currentUser) {
        List<AsnDetail> asnDetails = new ArrayList<>();
        for (Inventory inventory : list) {
          Double vmiNumber =   inventory.getNewReturnQty();
            inventory.setQuantity(inventory.getQuantity() - vmiNumber);
            Inventory toInv = new Inventory();
            BeanUtils.copyProperties(inventory, toInv);
            toInv.setAsnStockId(null);
            toInv.setAsnStockName(null);
            toInv.setFreezeQuantity(0.00);
            toInv.setInventoryId(null);
            toInv.setQuantity(vmiNumber);
//        inventory.
            String asnDetailNo = inventory.getAsnDetailNo();
            AsnDetail asnDetail = asnDetailService.getOne(new QueryWrapper<AsnDetail>().eq("detail_no", asnDetailNo));
            asnDetail.setStockId(inventory.getErpAreaId());
            asnDetail.setQty(vmiNumber);
            asnDetail.setBatchName(toInv.getBatchName());
            asnDetails.add(asnDetail);
            inventoryService.save(toInv);
            if (inventory.getQuantity() == 0) {
                inventoryService.removeById(inventory);
            } else {
                inventoryService.updateById(inventory);
            }
        }
        AsnMaster asnMaster = asnMasterService.getOne(new QueryWrapper<AsnMaster>().eq("bill_no", asnDetails.iterator().next().getBillNo()));

//        AsnMaster asnMaster = new AsnMaster();
//        asnMaster.setBillType(702);
//        asnMaster.setAsnType(1);

        strategyEnterService.resolveAsn(asnMaster, asnDetails, new BaseAssist());
    }

    /**
     * 先发配件
     *
     * @param ids
     * @param currentUser
     * @param qty
     */
    @Override
    public void start(Long id, CurrentUser currentUser, Double qty) {
        List<OutDetail> outSet = new ArrayList<>();
        WaveDetail waveDetail = waveDetailService.getById(id);
        List<Inventory> inventorieUpdate = new ArrayList<>();
        //待出库的所有物料
        List<SoDetail> soDetailList = soDetailService.list(new QueryWrapper<SoDetail>().in("wave_detail_id", id));
        //获取可出库的库存
        List<Inventory> inventoryList = inventoryService.list(new QueryWrapper<Inventory>()
                .in("item_code", waveDetail.getItemCode())
                                .eq("erp_area_id",start)
                //直发虚仓仓库id待定
                .notIn("cell_code", 285000, 285333)
        );
        //物料编码分组
        Map<String, List<Inventory>> inventoryMap = inventoryList.stream().collect(Collectors.groupingBy(Inventory::getItemCode));

        //获取待出库所有物料
        List<SoDetail> soDetails = transferBillService.subSoDetailAndPush(soDetailList, qty);

        for (SoDetail soDetail : soDetails) {
            OutDetail outDetail = new OutDetail();
            List<Inventory> inventories = inventoryMap.get(waveDetail.getItemCode());
            for (Inventory inv : inventories) {
                double invQty = inv.getQuantity() - inv.getAllotQuantity() - inv.getFreezeQuantity();
                if (soDetail.getSubQty() <= 0) {
                    break;
                }
                //如果库存不够分配
                if (invQty <= soDetail.getSubQty()) {
                    BeanUtils.copyProperties(soDetail, outDetail);
                    outDetail.setDeliveryQuantity(soDetail.getSubQty());
                    outDetail.setBoxCode(inv.getBoxCode());
                    outDetail.setCellCode(inv.getCellCode());
                    outDetail.setBatchName(inv.getBatchName());
                    outDetail.setErpAreaId(inv.getErpAreaId());
                    outSet.add(outDetail);
                    //可出库数量
                    soDetail.setSubQty(soDetail.getSubQty() - invQty);
//                    vmiNumber -= invQty;
                    inventorieUpdate.add(inv);
                } else {
                    //库存足够分配，全部填满SO的数量
                    BeanUtils.copyProperties(soDetail, outDetail);
                    outDetail.setDeliveryQuantity(soDetail.getSubQty());
                    outDetail.setBoxCode(inv.getBoxCode());
                    outDetail.setCellCode(inv.getCellCode());
                    outDetail.setBatchName(inv.getBatchName());
                    outDetail.setErpAreaId(inv.getErpAreaId());
                    outSet.add(outDetail);
                    //扣减已分配的库存数量
                    inv.setAllotQuantity(inv.getAllotQuantity() + soDetail.getSubQty());
                    break;
                }
            }
            //批量修改库存数量
            inventoryService.updateBatchById(inventories);
        }

        soDetailService.updateBatchById(soDetails);
        waveDetailService.updateState(waveDetail, qty);
        asyncService.asyncPushErp(inventorieUpdate, outSet, currentUser);
    }

    /**
     * 任务单直发虚仓
     *
     * @param createPickTask
     * @param currentUser
     */
    @Override
    public void manualCreatePickTask(CreatePickTask createPickTask, CurrentUser currentUser) {


//        List<UpdatePPF> ppfList = new ArrayList<>();
//        if (createPickTask.getBillNo().equals("") || createPickTask.getSoDetailId() == null || createPickTask.getCreatePickTaskDetails().size() <= 0) {
//            throw new ServiceException(CommonCode.PARAMETER_ERROR);
//        }
//        SoDetail soDetail = soDetailService.getById(createPickTask.getSoDetailId());
//        if (ObjectUtil.isNotEmpty(soDetail.getWaveDetailId())) {
//            WaveDetail waveDetail = waveDetailService.getById(soDetail.getWaveDetailId());
//            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该任务单已被"+waveDetail.getWaveCode()+"合并，请在"+waveDetail.getWaveCode()+"分配");
//        }
//        SoMaster soMaster = soMasterService.findBy("bill_no", createPickTask.getBillNo());
//        //分配数量
//        double allottedQuantity = 0;
//        List<AsnDetail> pushDetails = new ArrayList<>();
//        List<OutDetail> outDetailSet = new ArrayList<>();
//        for (CreatePickTaskDetail createPickTaskDetail : createPickTask.getCreatePickTaskDetails()) {
//            InventorySelectDto inventorySelectDto = inventoryService.findByInventoryId(new InventoryCriteria(createPickTaskDetail.getInventoryId())).get(0);
//            inventorySelectDto.setQuantity((inventorySelectDto.getQuantity() == null ? 0.0 : inventorySelectDto.getQuantity()) -createPickTaskDetail.getPickQuantity());
//            //生成出库单
//            AsnDetail asnDetail = asnDetailService.getOne(new QueryWrapper<AsnDetail>().eq("detail_no", inventorySelectDto.getAsnDetailNo()));
//            asnDetail.setQty(createPickTaskDetail.getPickQuantity());
//            asnDetail.setStockId(inventorySelectDto.getErpAreaId());
//            pushDetails.add(asnDetail);
//
//            //生成入库单
//            OutDetail outDetail = new OutDetail();
//            BeanUtils.copyProperties(soDetail, outDetail);
//            outDetail.setDeliveryQuantity(createPickTaskDetail.getPickQuantity());
//            outDetail.setBatchName(inventorySelectDto.getBatchName());
//            outDetail.setErpAreaId(inventorySelectDto.getErpAreaId());
//            outDetailSet.add(outDetail);
//            if (inventorySelectDto.getQuantity() <= 0) {
//                inventoryService.removeById(inventorySelectDto);
//            } else {
//                inventoryService.updateById(inventorySelectDto);
//            }
//            UpdatePPF updatePPF = new UpdatePPF();
//            updatePPF.setBillId(soDetail.getErpBillId());
//            updatePPF.setCommitQty( createPickTaskDetail.getPickQuantity());
//            updatePPF.setRowIndex(soDetail.getBomSplit());
//            ppfList.add(updatePPF);
//            allottedQuantity += createPickTaskDetail.getPickQuantity();
//            Integer invenotryId =createPickTaskDetail.getInventoryId();
//            Inventory inventory = inventoryService.getById(invenotryId);
//            inventory.setAllotQuantity(createPickTaskDetail.getPickQuantity());
//        }
//
//        //分配数，拣货数，复核数量 ++++
//        soDetail.setAllottedQuantity(allottedQuantity+soDetail.getAllottedQuantity());
//        soDetail.setPickQuantity(allottedQuantity + soDetail.getPickQuantity());
//        soDetail.setDeliveryQuantity(allottedQuantity + soDetail.getAllottedQuantity());
//        soDetailService.updateById(soDetail);
//        soMasterService.updateState(soMaster);
//        //修改分配数量
//        pushErpService.UpdatePPFeedAssignedQty(ppfList);
//        //直发虚仓入库
//        AsnMaster asnMaster = new AsnMaster();
//        asnMaster.setBillType(702);
//        asnMaster.setAsnType(1);
//        //直发虚仓入库
//        strategyEnterService.resolveAsn(asnMaster, pushDetails, new BaseAssist());
//        //直发虚仓出库
//        strategyErpService.resolveSo(soMaster, outDetailSet, new BaseAssist());


    }

    /**
     * 先发配件出库
     *
     * @param createPickTask
     * @param currentUser
     */
    @Override
    public void commitStart(CreatePickTask createPickTask, CurrentUser currentUser) {
        List<UpdatePPF> ppfList = new ArrayList<>();
        if (createPickTask.getBillNo().equals("") || createPickTask.getSoDetailId() == null || createPickTask.getCreatePickTaskDetails().size() <= 0) {
            throw new ServiceException(CommonCode.PARAMETER_ERROR);
        }
        SoDetail soDetail = soDetailService.getById(createPickTask.getSoDetailId());
        if (ObjectUtil.isNotEmpty(soDetail.getWaveDetailId())) {
            WaveDetail waveDetail = waveDetailService.getById(soDetail.getWaveDetailId());
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该任务单已被"+waveDetail.getWaveCode()+"合并，请在"+waveDetail.getWaveCode()+"分配");
        }
        SoMaster soMaster = soMasterService.findBy("bill_no", createPickTask.getBillNo());
        //分配数量
        double allottedQuantity = 0;
        List<AsnDetail> pushDetails = new ArrayList<>();
        List<OutDetail> outDetailSet = new ArrayList<>();
        for (CreatePickTaskDetail createPickTaskDetail : createPickTask.getCreatePickTaskDetails()) {
            InventorySelectDto inventorySelectDto = inventoryService.findByInventoryId(new InventoryCriteria(createPickTaskDetail.getInventoryId())).get(0);
            inventorySelectDto.setQuantity((inventorySelectDto.getQuantity() == null ? 0.0 : inventorySelectDto.getQuantity()) -createPickTaskDetail.getPickQuantity());
            //生成入库单
            OutDetail outDetail = new OutDetail();
            BeanUtils.copyProperties(soDetail, outDetail);
            outDetail.setDeliveryQuantity(createPickTaskDetail.getPickQuantity());
            outDetail.setMtoNo(soMaster.getTradeNo());
            outDetail.setBatchName(inventorySelectDto.getBatchName());
            outDetail.setErpAreaId(inventorySelectDto.getErpAreaId());
            outDetailSet.add(outDetail);
            UpdatePPF updatePPF = new UpdatePPF();
            updatePPF.setBillId(soDetail.getErpBillId());
            updatePPF.setCommitQty( createPickTaskDetail.getPickQuantity());
            updatePPF.setRowIndex(soDetail.getBomSplit());
            ppfList.add(updatePPF);
            allottedQuantity += createPickTaskDetail.getPickQuantity();
            Integer invenotryId =createPickTaskDetail.getInventoryId();
            Inventory inventory = inventoryService.getById(invenotryId);
            inventory.setAllotQuantity(createPickTaskDetail.getPickQuantity());

            if (inventory.getQuantity() <= 0) {
                inventoryService.removeById(inventorySelectDto);
            } else {
                inventoryService.updateById(inventorySelectDto);
            }
        }

        //分配数，拣货数，复核数量 ++++
        soDetail.setAllottedQuantity(allottedQuantity+soDetail.getAllottedQuantity());
        soDetail.setPickQuantity(allottedQuantity + soDetail.getPickQuantity());
        soDetail.setDeliveryQuantity(allottedQuantity + soDetail.getDeliveryQuantity());
        soDetailService.updateById(soDetail);
        soMasterService.updateState(soMaster);



        //todo  回传ERP
        //修改分配数量
        pushErpService.UpdatePPFeedAssignedQty(ppfList);
        //直发虚仓出库
        strategyErpService.resolveSo(soMaster, outDetailSet, new BaseAssist());


    }


    @Transactional
    public void inputBank(List<Inventory> inventories, Double vimNumber) {
        //默认值为0
        List<Inventory> inventoryList = new ArrayList<>();
        for (Inventory inventory : inventories) {
            Inventory inv = new Inventory();
            BeanUtils.copyProperties(inventory, inv);
            inv.setQuantity(0.00);
            inv.setAsnStockId(null); //id判空
            inv.setAsnStockName(null);
            inv.setInventoryId(null);//id为空
            inv.setBeforeCode(inventory.getBoxCode());
            Double quantity = inventory.getQuantity();
            double canBeQuantity = inventory.getQuantity() - inventory.getAllotQuantity() - inventory.getFreezeQuantity();
            //库存数量大于入库数量
            if (canBeQuantity >= vimNumber) {
                //新增一条数据
                inv.setQuantity(vimNumber);
                inventoryList.add(inv);
                //修改原库存
                inventory.setQuantity(quantity - vimNumber);
                //退出循环
                break;
            } else {
                vimNumber -= inventory.getQuantity();
                inv.setQuantity(quantity);
                inventoryList.add(inv);
                //修改原库存为0
                inventory.setQuantity(0.00);
            }
        }
        List<Integer> removeIds = inventories.stream().filter(item -> item.getQuantity() == 0).map(Inventory::getInventoryId).collect(Collectors.toList());
        //修改以前数据
        inventoryService.updateBatchById(inventories);
        //删除库存为0的数量
        inventoryService.removeByIds(removeIds);
        //新增库存
        inventoryService.saveBatch(inventoryList);
        List<String> asnDetailNo = inventoryList.stream().map(Inventory::getAsnDetailNo).collect(Collectors.toList());
        List<AsnDetail> asnDetails = asnDetailService.list(new QueryWrapper<AsnDetail>().in("detail_no", asnDetailNo));

        Map<String, AsnDetail> asnDetailMap = convertMap(asnDetails, AsnDetail::getBillNo);
        List<AsnDetail> pushDetails = new ArrayList<>();
        //找到源单
        for (Inventory inventory : inventoryList) {
            AsnDetail asnDetail = asnDetailMap.get(inventory.getAsnDetailNo());
            asnDetail.setQty(inventory.getQuantity());
            asnDetail.setStockId(inventory.getErpAreaId());
            pushDetails.add(asnDetail);
        }

        AsnMaster asnMaster = new AsnMaster();
        asnMaster.setBillType(702);
        asnMaster.setAsnType(1);
//        throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该货位不是集货位，不支持拣货");

        strategyEnterService.resolveAsn(asnMaster, pushDetails, new BaseAssist());
    }

    public void accomplishErp(AsnMaster asnMaster, String cellCode, CurrentUser currentUser) {
        List<AsnDetail> asnDetails = asnDetailService.findByBillNo(asnMaster.getBillNo());
        Integer areaId = cellInfoService.findbyCellCode(cellCode);
        List<AcceptInsert> acceptInserts = new ArrayList<>();
        
        // 现在加上了一个上架数量--只上架部分的数量--前提是产成品入库只有一个明细数据

        for (AsnDetail detail : asnDetails) {
            if (Double.doubleToLongBits(detail.getExpectQuantity()) == Double.doubleToLongBits(detail.getAcceptQuantity())) {
                continue;
            }
            detail.setAcceptQuantity(detail.getExpectQuantity());
            //批号任务单号当批号
            detail.setBatchName(detail.getMtoNo());
            detail.setStockId(areaId);
            detail.setQty(detail.getExpectQuantity());
            AcceptInsert acceptInsert = new AcceptInsert();

            acceptInsert.setMtoNo(detail.getMtoNo());
            //履约号
            acceptInsert.setAgreementNo(asnMaster.getAgreementNo());
            acceptInsert.setWareId(asnMaster.getWareId());
            acceptInsert.setWareName(asnMaster.getWareName());
            acceptInsert.setItemName(detail.getItemName());
            acceptInsert.setItemCode(detail.getItemCode());
            acceptInsert.setToBoxCode(codeRuleService.generateCellCodeRedis());
            acceptInsert.setBatchName(detail.getMtoNo());
            acceptInsert.setToPackDetailId(detail.getPackDetailId());
            acceptInsert.setToPackDescribe(detail.getPackDescribe());
            acceptInsert.setToTransRatio(detail.getTransRatio());
            // 这里的数量是前台填写的数量 detail.getExpectQuantity()->qty
            acceptInsert.setToQuantity(detail.getAcceptQuantity());
            acceptInsert.setToCellCode(cellCode);
            acceptInsert.setAcceptUserId(currentUser.getUserId());
            acceptInsert.setAcceptUserName(currentUser.getUserName());
            acceptInsert.setAcceptTime(DateUtil.now());
            acceptInsert.setBillType(0);
            acceptInsert.setAsnDetailNo(detail.getDetailNo());
            acceptInsert.setAsnBillNo(detail.getBillNo());
            // 质检-0
            acceptInsert.setQcState(0);
            acceptInsert.setCategoryId(asnMaster.getCategoryId());
            acceptInserts.add(acceptInsert);

            // 设置回传数量
//            detail.setQty(detail.getAcceptQuantity());

        }
        //Step1.创建收货单并确认
        acceptRecordService.saveAndConfirmAcceptRecord(acceptInserts);
        strategyEnterService.resolveAsn(asnMaster, asnDetails, new BaseAssist());

    }
    public void accomplishErp(List<String> detailIds, String cellCode, CurrentUser currentUser){
        List<AsnDetail> asnDetails = asnDetailService.listByIds(detailIds);
        String billNo = asnDetails.listIterator().next().getBillNo();
        List<SoDetail> soDetails = soDetailService.list(new QueryWrapper<SoDetail>().eq("bill_no", billNo));
        Map<String, SoDetail> soMap = convertMap(soDetails, SoDetail::getMergeNo);
        Integer areaId = cellInfoService.findbyCellCode(cellCode);
        AsnMaster asnMaster = asnMasterService.getOne(new QueryWrapper<AsnMaster>().eq("bill_no", billNo));
        List<AcceptInsert> acceptInserts = new ArrayList<>();
        for (AsnDetail detail : asnDetails) {

            if (Double.doubleToLongBits(detail.getExpectQuantity()) == Double.doubleToLongBits(detail.getAcceptQuantity())) {
                continue;
            }

            SoDetail soDetail = soMap.get(detail.getMtoNo());
            if (soDetail.getPickQuantity() < detail.getExpectQuantity()) {
                throw new ServiceException(CommonCode.SUPPLIER_CODE_EXISTS, soDetail.getItemCode()+"未拣货完毕");
            }
            detail.setAcceptQuantity(detail.getExpectQuantity());
            //批号任务单号当批号
            detail.setBatchName(detail.getMtoNo());
            detail.setStockId(areaId);
            detail.setQty(detail.getExpectQuantity());
            AcceptInsert acceptInsert = new AcceptInsert();

            acceptInsert.setMtoNo(detail.getMtoNo());
            //履约号
            acceptInsert.setAgreementNo(asnMaster.getAgreementNo());
            acceptInsert.setWareId(asnMaster.getWareId());
            acceptInsert.setWareName(asnMaster.getWareName());
            acceptInsert.setItemName(detail.getItemName());
            acceptInsert.setItemCode(detail.getItemCode());
            acceptInsert.setToBoxCode(codeRuleService.generateCellCodeRedis());
            acceptInsert.setBatchName(detail.getMtoNo());
            acceptInsert.setToPackDetailId(detail.getPackDetailId());
            acceptInsert.setToPackDescribe(detail.getPackDescribe());
            acceptInsert.setToTransRatio(detail.getTransRatio());
            // 这里的数量是前台填写的数量 detail.getExpectQuantity()->qty
            acceptInsert.setToQuantity(detail.getAcceptQuantity());
            acceptInsert.setToCellCode(cellCode);
            acceptInsert.setAcceptUserId(currentUser.getUserId());
            acceptInsert.setAcceptUserName(currentUser.getUserName());
            acceptInsert.setAcceptTime(DateUtil.now());
            acceptInsert.setBillType(0);
            acceptInsert.setAsnDetailNo(detail.getDetailNo());
            acceptInsert.setAsnBillNo(detail.getBillNo());
            // 质检-0
            acceptInsert.setQcState(0);
            acceptInsert.setCategoryId(asnMaster.getCategoryId());
            acceptInserts.add(acceptInsert);

            // 设置回传数量
//            detail.setQty(detail.getAcceptQuantity());

        }
        //Step1.创建收货单并确认
        acceptRecordService.saveAndConfirmAcceptRecord(acceptInserts);
        strategyEnterService.resolveAsn(asnMaster, asnDetails, new BaseAssist());
    }

}
